package com.cskaoyan.service;

import com.cskaoyan.bean.GoodsExample;
import com.cskaoyan.bean.GrouponRules;
import com.cskaoyan.bean.GrouponRulesExample;
import com.cskaoyan.mapper.GoodsMapper;
import com.cskaoyan.mapper.GrouponRulesMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GrouponServiceImpl implements GrouponService{

    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Override
    public Map<String, Object> listGroupon(Integer page, Integer limit, Integer goodsId, String sort, String order) {

        PageHelper.startPage(page,limit);
        GrouponRulesExample grouponRulesExample = new GrouponRulesExample();
        grouponRulesExample.setOrderByClause(sort + " " + order);
        if (goodsId != null){
            GrouponRulesExample.Criteria criteria = grouponRulesExample.createCriteria();
            criteria.andGoodsIdEqualTo(goodsId);
        }
        List<GrouponRules> items = grouponRulesMapper.selectByExample(grouponRulesExample);
        int total = items.size();
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("items",items);
        return map;
    }

    @Override
    public GrouponRules publishGroupon(GrouponRules grouponRules) {
        Map<String, Object> map = goodsMapper.selectMapByGoodsId(grouponRules.getGoodsId());
        grouponRules.setGoodsName((String) map.get("name"));
        grouponRules.setPicUrl((String) map.get("pic_url"));
        grouponRules.setAddTime((Date) map.get("add_time"));
        grouponRules.setUpdateTime((Date) map.get("update_time"));
        grouponRules.setDeleted(false);
        grouponRulesMapper.insert(grouponRules);
        return grouponRules;
    }

    @Override
    public int editGroupon(GrouponRules grouponRules) {

        int update = grouponRulesMapper.updateByPrimaryKey(grouponRules);
        return update;
    }

    @Override
    public int deleteGroupon(GrouponRules grouponRules) {
        grouponRules.setDeleted(true);
        int update = grouponRulesMapper.updateByPrimaryKey(grouponRules);
        return update;
    }
}
